/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package org.kunteng.yunac.modules.sys.web;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.kunteng.yunac.common.utils.StringUtils;
import org.kunteng.yunac.common.web.BaseController;
import org.kunteng.yunac.modules.sys.entity.User;
import org.kunteng.yunac.modules.sys.service.SystemService;
import org.kunteng.yunac.modules.sys.utils.UserUtils;

/**
 * 用户Controller
 * @author ThinkGem
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

	private String uploadedImageDir = "/static/tmp/";

	@Autowired
	private SystemService systemService;
	
	@ModelAttribute
	public User get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return systemService.getUser(id);
		}else{
			return new User();
		}
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "profile")
	public String form(User user, Model model) {
		model.addAttribute("user", UserUtils.getUser());
		return "modules/sys/profile";
	}

	/**
	 * 个人中心信息提交
	 * @param user
	 * @param request
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "save")
	public String updateUserInfo(User user, HttpServletRequest request, Model model) {
//		if(Global.isDemoMode()){
//			addMessage(redirectAttributes, "演示模式，不允许操作！");
//			return "redirect:" + adminPath + "/sys/user/list?repage";
//		}

		if (!beanValidator(model, user)){
			return form(user, model);
		}

		User currentUser = UserUtils.getUser();
		user.setId(currentUser.getId());

		String avatarPath = (String) request.getSession().getAttribute("avatar");
		String logoPath = (String) request.getSession().getAttribute("logo");

//		System.out.println(">>>>>>>>>>>>>>>>>>"+currentUser.getAvatar());
//		System.out.println(">>>>>>>>>>>>>>>>>>"+currentUser.getLogo());
//		System.out.println(">>>>>>>>>>>>>>>>>>avatarPath: "+avatarPath);
//		System.out.println(">>>>>>>>>>>>>>>>>>logoPath: "+logoPath);

		if (avatarPath!=null) {
			System.out.println("设置 avatar: "+avatarPath);
			user.setAvatar(avatarPath);
		}
		if (logoPath!=null) {
			System.out.println("设置 logo: "+logoPath);
			user.setLogo(logoPath);
		}

		// 保存用户信息

		User use1r = UserUtils.getUser();		systemService.updateUserInfo(user);//saveUser(user);
		// 清除当前用户缓存
		UserUtils.clearCache();
//		if (user.getAccount().equals(UserUtils.getUser().getAccount())){
//			UserUtils.clearCache();
//			//UserUtils.getCacheMap().clear();
//		}
		model.addAttribute("successMessage","保存用户'" + user.getAccount() + "'信息成功");
		return "modules/sys/profile";
	}

	@RequestMapping(value = "passwd", method = RequestMethod.GET)
	public String passwdPage(Model model) {
		return "modules/sys/changePwd";
	}
	/**
	 * 验证登录名是否有效
	 * @param loginName
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("user")
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String loginName) {
		if (loginName !=null && systemService.getUserByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 修改个人用户密码
	 * @param oldPassword
	 * @param newPassword
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "modifyPwd", method = RequestMethod.POST)
	public String modifyPwd(String oldPassword, String newPassword, Model model) {
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
			if (SystemService.validatePassword(oldPassword, user.getPasswd())){
				systemService.updatePasswordById(user.getId(), user.getAccount(), newPassword);
//				model.addAttribute("message", "修改密码成功");
				return "{\"code\":200,\"msg\":\"修改密码成功\"}";
			}else{
//				model.addAttribute("message", "修改密码失败，旧密码错误");
				return "{\"code\":401,\"msg\":\"旧密码错误\"}";
			}
		}
//		model.addAttribute("user", user);
		return "{\"code\":204,\"msg\":\"密码不能为空\"}";
	}


	@RequestMapping(value = "headImage")
	public String initHeadImage(Model model) {
		User user = UserUtils.getUser();
		String path = UserUtils.getUserInheritAvatar(user);
		if (path == null) {
			path = "/static/img/user.png";
		}
		model.addAttribute("path",path);
		return "modules/sys/imagePreview";
	}

	@RequestMapping(value = "logoImage")
	public String initLogoImage(Model model) {
		User user = UserUtils.getUser();
		String path = UserUtils.getUserInheritLogo(user);
		if (path == null) {
			path = "/static/img/yunac2.png";
		}
		model.addAttribute("path",path);
		return "modules/sys/logoPreview";
	}

	@RequestMapping(value = "uploadHeadImage", method = RequestMethod.POST)
	public String uploadHeadImage(@RequestParam(value = "imgFile", required = false) MultipartFile file, HttpServletRequest request, Model model) throws IOException {
		System.out.println("开始上传头像");
		String path = request.getSession().getServletContext().getRealPath(uploadedImageDir);
		String OrigiName = file.getOriginalFilename();
		String extName = OrigiName.substring(OrigiName.lastIndexOf('.'));
		String fileName = UUID.randomUUID().toString() + extName;
		System.out.println(path);
		File targetFile = new File(path, fileName);
		if(!targetFile.getParentFile().exists()){
			targetFile.getParentFile().mkdirs();
		}
		//保存
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.getSession().setAttribute("avatar",uploadedImageDir+fileName);

//		return "<img src='"+request.getContextPath()+"/upload/"+fileName+"' />";
		model.addAttribute("path",uploadedImageDir+fileName);
		model.addAttribute("width",65);
		model.addAttribute("height",65);
		return "modules/sys/imagePreview";
	}

	@RequestMapping(value = "uploadLogoImage", method = RequestMethod.POST)
	public String uploadLogoImage(@RequestParam(value = "imgFile", required = false) MultipartFile file, HttpServletRequest request, Model model) throws IOException {
		System.out.println("开始上传logo");
		String path = request.getSession().getServletContext().getRealPath(uploadedImageDir);
		String origiName = file.getOriginalFilename();
		String extName = origiName.substring(origiName.lastIndexOf('.'));
		String fileName = UUID.randomUUID().toString() + extName;
		System.out.println(path);
		File targetFile = new File(path, fileName);
		if(!targetFile.getParentFile().exists()){
			targetFile.getParentFile().mkdirs();
		}
		//保存
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.getSession().setAttribute("logo",uploadedImageDir+fileName);

//		return "<img src='"+request.getContextPath()+"/upload/"+fileName+"' />";
		model.addAttribute("path",uploadedImageDir+fileName);
		model.addAttribute("width",65);
		model.addAttribute("height",65);
		return "modules/sys/logoPreview";
	}

}
